import json
import logging
import time

from apscheduler.schedulers.blocking import BlockingScheduler
from sqlalchemy import create_engine, text

from apps.settingApi.api.timerTask.model import timerTaskConfigModel
from apps.settingApi.api.timerTask.taskData import taskInfo
from apps.settingApi.switchCase.casePrimaryKey import caseGetPrimaryKeyData
from comm.dbConnect import get_yun_session
# from comm.sqlalchemyConfig import scheduler
scheduler = BlockingScheduler()
def my_job(job_id):
    # 暂停任务
    scheduler.pause_job(job_id)
    print('执行了任务')
    try:
        seconds = taskInfo()
    except:
        seconds = 10
    try:
        # 修改下次执行时间
        scheduler.reschedule_job(job_id=job_id, trigger='interval', seconds=seconds)
    except Exception as e:
        print('定时任务执行时异常')
        logging.info('定时任务执行时异常' + repr(e))
    finally:
        print('启动任务')
        scheduler.resume_job(job_id)

def add_task(trigger='interval', seconds=5):
    """
    :param task_name:定时任务名称(tx_timer_taskb表中的id)
    :param func:
    :param trigger:
    :param seconds:
    :return:
    """
    job_id = caseGetPrimaryKeyData()
    # job = scheduler.add_job(func=my_job, trigger="interval", seconds=seconds,args=[])

    # 追加任务
    db = get_yun_session()
    scheduler.add_job(func=my_job, trigger=trigger, seconds=seconds,args=[job_id],id=job_id)
    exit_id = db.query(timerTaskConfigModel).filter(
        timerTaskConfigModel.id == '2024053114505639250008110').first()
    if exit_id!=None and exit_id.status==True:
        logging.info('启动定时任务' + job_id)
        # 启动定时任务
        scheduler.start()
    return job_id
def remove_task(id):
    try:
        scheduler.remove_job(id)
        logging.info('停止定时任务' + id)
    except:
        pass
    return

# add_task(seconds=5)
